<template>
  <div>
    <div class="wrap">
      <div class="content">
        <h3>添加货柜</h3>
        <div class="form-content">
          <el-form ref="form" :model="currentForm" label-width="80px" :rules="rules">
            <el-form-item label="运输类型" prop="transferType" >
              <el-radio-group v-model="currentForm.transferType" @change="clearBoxIds">
                <el-radio
                  v-for="item in transferTypeList"
                  :key="item.transferType"
                  :label="item.transferType"
                >
                  {{item.typeName}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="form-item">
              <el-form-item label="货柜名称" prop="containerName">
                <el-input v-model="currentForm.containerName" placeholder="选填，不填系统将默认生成货柜名称"></el-input>
              </el-form-item>
              <el-form-item
                v-for="item in showFormItem"
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
              >
                <template v-if="item.type === 'date'">
                  <el-date-picker
                    v-model="currentForm[item.prop]"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </template>
                <template v-else>
                  <el-input v-model="currentForm[item.prop]" :placeholder="item.placeholder ? item.placeholder : '请填写'"></el-input>
                </template>
              </el-form-item>
            </div>


            <el-form-item label="装柜货物" prop="boxIds"></el-form-item>
            <div class="box-table">
              <div class="box-table-header mgb10">
                <div class="left">
                  当前添加箱子数量：<span class="font-red">{{currentForm.boxIds.length}}</span>
                </div>
                <div class="right">
                  <el-select v-model="queryParams.type" class="mgr20">
                    <el-option label="全部类型" value=""></el-option>
                    <el-option label="一件代发" value="one_shipping"></el-option>
                    <el-option label="暂存中转" value="middle"></el-option>
                    <el-option label="ML直送" value="mkd_full"></el-option>
                    <el-option label="ML直送(CBT)" value="mkd_cbt_full"></el-option>
                    <el-option label="线下配送" value="offline_delivery"></el-option>
                  </el-select>

                  <el-input v-model="queryParams.keyword" style="width: 200px" placeholder="搜索货件单号"></el-input>

                </div>
              </div>
              <div class="table">
                <el-table
                  :data="computedTable"
                  border
                  default-expand-all
                  row-key="id"
                  :tree-props="{children: 'boxList', hasChildren: 'hasChildren'}"
                  v-loading="tableLoading"
                  :row-class-name="tableRowClassName"
                  class="container-box-table"
                >
                  <el-table-column
                    prop="shipmentNo"
                    label="货件单号"
                    align="center"
                    min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="boxId"
                    label="货件箱数/箱唛"
                    align="center"
                    min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="shipmentType"
                    label="货件类型"
                    align="center"
                    min-width="180"
                  >
                    <template v-slot="{row}">
                      {{getShipmentTypeStr2(row.shipmentType)}}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="weight"
                    label="实重（kg）"
                    align="center"
                    min-width="100"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="length"
                    label="长（cm）"
                    align="center"
                    min-width="100"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="width"
                    label="宽（cm）"
                    align="center"
                    min-width="100"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="height"
                    label="高（cm）"
                    align="center"
                    min-width="100"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="volumeWeight"
                    label="体积重（6000）"
                    align="center"
                    min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="squareNumber"
                    label="方数"
                    align="center"
                    min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="calWeight"
                    label="计费重"
                    align="center"
                    min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="checked"
                    label="选择"
                    align="center"
                    width="100"
                    fixed="right"
                  >
                    <template v-slot="{row}">
                      <template v-if="row.dataType === 'shipment'">
                        <el-checkbox :value="checkAllBoxId(row)" @change="checkShipment(row)"></el-checkbox>
                      </template>
                      <template v-else>
                        <el-checkbox :value="currentForm.boxIds.includes(row.boxId)" @change="checkBoxId(row)"></el-checkbox>
                      </template>
                    </template>
                  </el-table-column>

                </el-table>
              </div>
            </div>


          </el-form>
        </div>
      </div>
    </div>
    <footer-nav>
      <el-button type="primary" @click="submit" :loading="loading">确认</el-button>
    </footer-nav>
  </div>
</template>

<style>

.container-box-table .box-row {
  background: #f5f7fa;
}
</style>

<script>
import shippingPlanDataMixin from "@/views/shippingPlan/mixin/shippingPlanDataMixin";
import {getShipmentWaitCabinetBox} from "@/api/shipmentV2";
import {getShipmentTypeStr2} from "@/utils/shipment";
import {createContainer} from "@/api/container";
import FooterNav from "@/components/Common/FooterNav.vue";
import BoxSize from "@/views/shipment/components/BoxSize.vue";
import {formItem} from "@/views/container/configs/formItem";
import containerStorageMixin from "@/views/container/mixins/containerStorageMixin";


const localStorageKey = 'addContainerFields'
export default {
  name: 'addContainer',
  components: {FooterNav},
  mixins: [shippingPlanDataMixin, containerStorageMixin],
  computed: {
    computedTable(){
      return this.tableData.filter(item=>{
        // 空运的可以选空运 海运的可以选海运
        if(this.transferTypeListType.findIndex(_item => _item.transferType === item.transferType) === -1){
          return false
        }
        if(this.queryParams.type){
          return item.shipmentType === this.queryParams.type
        }
        if(this.queryParams.keyword){
          if(item.shipmentNo.includes(this.queryParams.keyword)){
            return true
          }else{
            return false
          }
        }
        return true
      })
    },
    // 当前选择的type 空运还是海运
    currentTransferTypeType(){
      return this.transferTypeList.find(item => item.transferType === this.currentForm.transferType)?.type
    },
    // 当前类型对应的运输类型
    transferTypeListType(){
      return this.transferTypeList.filter(item => item.type === this.currentTransferTypeType)
    },
    isAir(){
      return this.currentForm.transferType === 'air_fast' || this.currentForm.transferType === 'air_slow';
    },
    showFormItem(){
      return this.formItem.filter(item => item.transferType.includes(this.currentForm.transferType))
    },
  },
  data(){
    return {
      loading: false,
      tableLoading: false,
      currentForm: {
        containerName: '',
        transferType: '',
        containerNo: '',
        GPS: '',
        flightNo: '',
        ladingNo: '',
        boxIds: [],
        bookingNum: '', // 订舱号
        sealNum: '', // 封条号
        shipsName: '', // 船名
        flightNum: '', // 航次
        startPort: '', // 起始港
        targetPort: '', // 目的港
        boxWeight: '', // 箱型重量
        installDate: '', // 装柜日期
        customBroker: '', // 报关行
        customClearance: '', // 清关行
      },

      queryParams: {
        type: '',
        keyword: '',
      },
      tableData: [],
      rules: {
        transferType: [
          // { required: true, message: '请选择运输类型', trigger: 'change' }
        ],
        containerNo: [
          // { required: true, message: '请输入货柜编号', trigger: 'blur' },
        ],
        GPS: [
          // { required: true, message: '请输入GPS编号', trigger: 'blur' },
        ],
        flightNo: [
          // { required: true, message: '请输入航班号', trigger: 'blur' },
        ],
        ladingNo: [
          // { required: true, message: '请输入提单号', trigger: 'blur' },
        ],
      },
      formItem,
    }
  },
  created() {
    this.setCurrentForm()
    this.getData()
  },
  methods: {
    // 根据缓存填充上一次的值
    setCurrentForm(){
      let obj = localStorage.getItem(localStorageKey)
      if(obj){
        this.rememberObj = JSON.parse(obj)
        for (const key in this.rememberObj) {
          if(this.rememberFields.includes(key) && this.rememberObj[key] !== ''){
            this.currentForm[key] = this.rememberObj[key]
          }
        }
      }
    },
    getShipmentTypeStr2,
    tableRowClassName({row}){
      if(row.dataType === 'box'){
        return 'box-row'
      }
      return ''
    },
    getData(){
      this.tableLoading = true
      getShipmentWaitCabinetBox()
        .then(res=>{
          this.tableLoading = false
          this.tableData = res.data
        })
    },
    finishWarehouseApi(){
      this.currentForm.transferType = this.transferTypeList[0].transferType
    },
    // 这个货件单是不是已经全选
    checkAllBoxId(row){
      const boxList = row.boxList
      return boxList.every(item=>this.currentForm.boxIds.includes(item.boxId))
    },
    // 选择这个货件单
    checkShipment(row){
      const boxList = row.boxList
      if(this.checkAllBoxId(row)){
        boxList.forEach(item=>{
          const index = this.currentForm.boxIds.findIndex(boxId => boxId === item.boxId)
          if(index !== -1){
            this.currentForm.boxIds.splice(index, 1)
          }
        })
      }else{
        boxList.forEach(item=>{
          if(!this.currentForm.boxIds.includes(item.boxId)){ // 如果当前货件单没有选中的话
            this.currentForm.boxIds.push(item.boxId)
          }
        })
      }
    },
    checkBoxId(row){
      if(this.currentForm.boxIds.includes(row.boxId)){
        this.currentForm.boxIds = this.currentForm.boxIds.filter(item=>item !== row.boxId)
      }else{
        this.currentForm.boxIds.push(row.boxId)
      }
    },
    clearBoxIds(){
      console.log(this.isAir)
      this.currentForm.boxIds = []
    },
    submit(){
      this.$refs.form.validate(valid=>{
        if(valid){
          if(this.currentForm.boxIds.length === 0){
            this.$message.warning('请选择箱唛')
            return
          }

          // 清除多余的属性
          const allProps = this.formItem.map(item => item.prop)
          const showProps = this.showFormItem.map(item => item.prop)
          allProps.forEach(prop=>{
            if(!showProps.includes(prop)){
              this.currentForm[prop] = '';
            }
          })
          this.setLocalStorage(this.currentForm)

          this.loading = true
          createContainer(this.currentForm)
            .then(res=>{
              this.loading = false
              if(res.error === 0){
                this.$successMessage(res.message)
                if(!this.isAir){
                  this.$router.push({
                    name: 'containerList',
                    params: {
                      needRefresh: true,
                    }
                  })
                }else{
                  this.$router.push({
                    name: 'airContainerList',
                    params: {
                      needRefresh: true,
                    }
                  })
                }
                this.clearForm()

              }else{
                this.$errorMessage(res.message)
              }
            })
        }
      })
    },
    clearForm(){
      this.getData()
      this.currentForm.transferType = this.transferTypeList[0].transferType
      this.currentForm.containerNo = ''
      this.currentForm.GPS = ''
      this.currentForm.flightNo = ''
      this.currentForm.ladingNo = ''
      this.currentForm.boxIds = [];
    },
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 10px 30px 80px;
  .content{
    padding: 0px 0 0;
    .box-table{
      margin: 20px 0;
      .box-table-header{
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .form-content{
    .form-item{
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      .el-form-item{
        width: 40%;
      }
    }
  }
}
</style>
